package org.tea.inventory.log.job;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * 清除过期日志记录
 *
 * @author gourd.hu
 */
@Slf4j
@Component
public class DelExpireLog {

    @Autowired
    private AsyncTaskExecutor asyncTaskExecutor;
    /**
     * 默认30天
     */
    @Value("${logging.operate.expire.days:180}")
    private int expireDays;

    /**
     * 每天0点执行一次删除过期日志
     */
    /*@Scheduled(cron = "0 0 0 * * ?")
    public void doTask() {
        log.info(">o< 删除过期日志定时任务开始执行： " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()) + "  " + Thread.currentThread().getName());
        while (true) {
            PageHelper.startPage(1, 500);
            SysOperateLog operateLog = new SysOperateLog();
            operateLog.setExpireTime(LocalDateTime.now());
            List<SysOperateLog> logs = operateLogService.getByAll(operateLog);
            PageInfo<SysOperateLog> pageInfo = new PageInfo<>(logs);

            List<SysOperateLog> logPOS = pageInfo.getList();
            if (CollectionUtils.isEmpty(logPOS)) {
                break;
            }
            List<Long> logIds = logPOS.stream().map(e -> e.getId()).collect(Collectors.toList());
            asyncTaskExecutor.execute(() -> operateLogService.deleteLogs(logIds));
        }
        log.info(">o< 删除过期日志定时任务结束： " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()) + "  " + Thread.currentThread().getName());
    }

    *//**
     * 异步保存日志信息
     *
     * @param joinPoint
     * @param startTime
     * @param sysOperateLog
     *//*
    @Async
    public void asyncSaveLog(HttpServletRequest request, ProceedingJoinPoint joinPoint, Long startTime, SysOperateLog sysOperateLog) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        OperateLog operateLog = signature.getMethod().getAnnotation(OperateLog.class);
        if(operateLog != null){
            // 描述
            sysOperateLog.setDescription(operateLog.description());
            // 模块
            sysOperateLog.setModuleName(operateLog.moduleName());
            // 业务
            sysOperateLog.setBusinessName(operateLog.businessName());
            UserInfo userInfo = UserUtil.getUser();
            if (userInfo !=null) {
                sysOperateLog.setLoginId(userInfo.getLoginId());
            }else{
                sysOperateLog.setLoginId("admin123");
            }
        }
        // 设置过期时间
        LocalDateTime expireTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0)).plusDays(expireDays);
        sysOperateLog.setExpireTime(expireTime);
        // 单位毫秒
        Long requestTime =startTime ==null? null: (System.currentTimeMillis() - startTime);

        // 方法名
        sysOperateLog.setMethodName(signature.getName());
        // 方法类型
        sysOperateLog.setMethodType(request.getMethod());
        // 请求路径
        sysOperateLog.setRequestUrl(request.getRequestURL().toString());
        // 请求参数
        sysOperateLog.setRequestParam(getParam(joinPoint, signature));
        // 获取用户ip
        sysOperateLog.setRequestIp(IpAddressUtil.getIpAddr(request));
        // 请求耗时
        sysOperateLog.setRequestTime(requestTime);
        if(StringUtils.isNotBlank(sysOperateLog.getLoginId())){
            sysOperateLogDao.insertSelective(sysOperateLog);
        }
    }

    *//**
     * 获取请求参数
     * @param joinPoint
     * @param signature
     * @return
     *//*
    private String getParam(JoinPoint joinPoint, MethodSignature signature) {
        StringBuilder params = new StringBuilder("{");
        // 参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = signature.getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ");
                params.append(argNames[i]).append(":");
                params.append(argValues[i]);
            }
        }
        params.append(" }");
        return params.toString();
    }*/


}
